//
//  SFTabbarController.swift
//  SeeFM_Swift
//
//  Created by CBCT_MBP on 2021/5/19.
//

import UIKit

class SFTabbarController: UITabBarController {

    var vcs: [SFBaseController]?
    var currentNavigationVC: SFNavigationController?
    let mainTabbar = SFTabbar()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let home = SFHomeController.init()
        let find = SFFindController.init()
        let message = SFMessageController.init()
        let mine = SFUserController.init()
        mine.isTabMe = true
        
        vcs = [home,find,message,mine]
        
        for idx in 0...3 {
            guard let vc = vcs?[idx] else { return }
            let nav = SFNavigationController(rootViewController: vc)
            addChild(nav)
        }
        self.selectedIndex = 0
        
        setValue(mainTabbar, forKey: "tabBar")
        mainTabbar.tabbarClickClosure = { [weak self] (state: TabbarSelectState) in
            
            if AppHelper.isCheck {
                self!.selectedIndex = self!.mainTabbar.states.firstIndex(of: state) ?? 0
                return true
            }else {
                if state == .message || state == .mine {
                    if Login.isLogin() {
                        self!.selectedIndex = self!.mainTabbar.states.firstIndex(of: state) ?? 0
                        return true
                    }else {
                        AppHelper.openLogin { [weak self] res in
                            if res {
                                self?.selectedIndex = self!.mainTabbar.states.firstIndex(of: state) ?? 0
                            }
                        }
                        return false
                    }
                }else {
                    self!.selectedIndex = self!.mainTabbar.states.firstIndex(of: state) ?? 0
                    return true
                }
            }
        }
    }
    
    override var selectedIndex: Int {
        willSet{
            let vc = self.vcs?[newValue]
            self.currentNavigationVC = vc?.navigationController as? SFNavigationController
        }
    }

}
